package com.wgd.mqttandroidwgd;

import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.itfitness.mqttlibrary.MqttAndroidClient;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.UUID;

/**
 * @Description: java类作用描述
 * @Author: 作者名
 * @CreateDate: 2022/1/26 16:59
 * @UpdateUser: 更新者：
 * @UpdateDate: 2022/1/26 16:59
 * @UpdateRemark: 更新说明：
 */
public class MQTTHelper {
    private MqttAndroidClient mqttClient;
    private MqttConnectOptions connectOptions;
    private IMqttActionListener mqttActionListener;

    public MQTTHelper(Context context, String serverUrl, String name, String pass) {
        String clientId = UUID.randomUUID().toString();

        mqttClient = new MqttAndroidClient(context, serverUrl, clientId);
        connectOptions = new MqttConnectOptions();
        connectOptions.setCleanSession(true);//是否会话持久化
        connectOptions.setConnectionTimeout(30);//连接超时时间
        connectOptions.setKeepAliveInterval(10);//发送心跳时间
        if (!TextUtils.isEmpty(name)) {
            connectOptions.setUserName(name); //如果设置了认证，填的用户名
        }
        if (!TextUtils.isEmpty(pass)) {
            connectOptions.setPassword(pass.toCharArray());//用户密码
        }
    }

    /**
     * 连接
     *
     * @param mqttCallback 接到订阅的消息的回调
     * @param isFailRetry  失败是否重新连接
     */
    private int mConnectCount = 0;

    public void connect(String topic, boolean isFailRetry, MqttCallback mqttCallback) {
        mConnectCount = 0;
        mqttClient.setCallback(mqttCallback);
        if (mqttActionListener == null) {
            mqttActionListener = new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.e("aaa", "连接成功");
                    subscribe(topic);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    //失败重连
                    Log.e("aaa", "连接失败重试:" + exception.getMessage());
                    if (isFailRetry) {
                        if (mConnectCount < 5) {
                            try {
                                SystemClock.sleep(1000);
                                mqttClient.connect(connectOptions, null, mqttActionListener);
                            } catch (MqttException e) {
                                throw new RuntimeException(e);
                            }
                            mConnectCount++;
                        }
                    }
                }
            };
        }
        try {
            mqttClient.connect(connectOptions, null, mqttActionListener);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 订阅
     */
    private void subscribe(String topic) {
        try {
            mqttClient.subscribe(topic, 2);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发布
     */
    public void publish(String topic, String message) {
        MqttMessage msg = new MqttMessage();
        msg.setRetained(false);
        msg.setPayload(message.getBytes());
        msg.setQos(2);
        try {
            mqttClient.publish(topic, msg);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开连接
     */
    public void disconnect() {
        try {
            mqttClient.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}